<template>
  <div class="app-container">
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>批量导入员工</span>
      </div>
      <!-- card body -->
      <UploadExcel :before-upload="beforeUpload" :on-success="handleSuccess" />
    </el-card>
  </div>
</template>

<script>
// import * as XLSX from 'xlsx'
import { importEmployees } from '@/api/employees'
import { formatExcelDate } from '@/utils/index.js'
export default {
  name: 'Import',
  // created() {
  //   console.log(XLSX)
  // },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 2
      if (isLt1M) {
        return true
      }
      this.$message({
        message: '请不要上传大于2M的文件.',
        type: 'warning'
      })
      return false
    },
    // 获取excle员工数据
    async handleSuccess({ results, header }) {
      // console.log(results, header)
      const enResults = this.transformResults(results)
      await importEmployees(enResults)
      this.$message.success('上传成功')
      this.$router.back()
      // console.log(enResults)
      // this.tableData = results
      // this.tableHeader = header
    },
    // 中文名转英文名
    transformResults(results) {
      const map = {
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      const newResults = []
      results.forEach(item => {
        const everuObj = {}
        for (const key in item) {
          if (map[key] === 'timeOfEntry' || map[key] === 'correctionTime') {
            item[key] = formatExcelDate(item[key], '-')
          } else {
            everuObj[map[key]] = item[key]
          }
          everuObj[map[key]] = item[key]
        }
        newResults.push(everuObj)
      })
      return newResults
    }
  }
}
</script>

<style></style>
